package com.syphernova.learning.amst3;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;


public class RetrieveJSON extends AsyncTask<String, Void, String> {

	Context c;
	
	public RetrieveJSON(Context c){
		this.c = c;
	}
	
	private static final String TAG = "RetrieveJSON";

	@Override
	protected String doInBackground(String... urls) {
		int xvalue = Integer.parseInt(urls[0]);
		String urlToFetch = urls[1];
		String pageToFetch = urls[2];
		Socket sock = null;
		int port = 80;
		Scanner in  = null;
		String XthLine = "DumbLine";
		
		if(xvalue<=0){
			xvalue = 1;
		}
		
		int x = 0;
		//Log.d(TAG, urlToFetch);
		try {
			sock = new Socket(urlToFetch, port);
			in  = new Scanner(sock.getInputStream());
			
			DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
			String request ="GET " + pageToFetch + " HTTP/1.1\r\nHost: earthquake.usgs.gov\r\nAccept: */*\r\nAccept-Language: en-us\r\nUser-Agent: Chrome/37.0.2049.0\r\n\r\n"; 
			dOut.write(request.getBytes());
			
			String str = "";
			while(in.hasNext()){
				str = in.nextLine();
				if(str.equals("Connection: keep-alive")){
					str = in.nextLine();
					break;
				}
			}
			x = 0;
			while(in.hasNext() && x<xvalue){
				XthLine = in.nextLine();
				Log.d(TAG, XthLine);
				x++;
			}
			
		} catch (IOException e) {
			Log.d(TAG, "IO Exception occured during Socket opening!");
			e.printStackTrace();
		}finally{
			if(sock != null){
				try {
					sock.close();
				} catch (IOException e) {
					Log.d(TAG, "Socket could not be closed!");
				}
			}
			if(in != null){
				in.close();
			}
		}
		return XthLine;
	}
	
	protected void onPostExecute(){
		Toast.makeText(c, "Received Page!", Toast.LENGTH_LONG).show();
		
	}

}
